package public

import (
	"encoding/json"
	"fmt"
	"github.com/wycto/weigo"
	"github.com/wycto/weigo/datatype"
	"github.com/wycto/weigo/log"
	"github.com/wycto/weigo/msg"
	"github.com/wycto/weigo/tools/datetime"
	"github.com/wycto/weigo/tools/encrypt"
	"weigo-blog/app/model"
)

type RCTController struct {
	weigo.Controller
}

func (c *RCTController) Php() {
	weigo.Log.Write("dsfgsdf")
	log.Write("234324")
	fmt.Println(c.Context.Param)
	ii := datatype.Row{"InfoArr": c.Context.Param.Get("InfoArr")}
	m := datatype.Row{}
	fmt.Println("argument: ", ii.GetType("InfoArr"))
	ii.SetStruct("InfoArr", &m)
	fmt.Println(m)
	fmt.Println(m.GetString("ClassName"))
	fmt.Println(m.GetString("MethodName"))
	fmt.Println(m.GetString("Sign"))
	fmt.Println(m.GetString("Argument"))

	var argument []interface{}
	m.SetStruct("Argument", &argument)
	fmt.Println("argument: ", m.GetString("Argument"))
	fmt.Println("argument: ", m.GetType("Argument"))

	argument1 := m.GetString("Argument")
	fmt.Println("argument1: ", argument1)

	argument2 := m.Get("Argument")
	fmt.Println("argument2: ", argument2)

	m33 := make(map[string]string)
	json.Unmarshal([]byte(c.Context.Param.GetString("InfoArr")), &m33)
	fmt.Println("argument3: ", m33)

	if c.Context.IsPost() {

		//参数校验
		if c.Context.NotHasOrEmpty("username", "password") {
			c.ResponseErrorMessage(msg.ParamsMissingORInvalid, nil)
			return
		}

		//存在校验
		row, err := model.UserModel().Where(&datatype.Row{"username": c.Context.Param.GetString("username"), "password": encrypt.MD5(c.Context.Param.GetString("password"))}).Find()
		if err != nil {
			c.ResponseErrorMessage(msg.DataAccountNotExists, nil)
			return
		}

		//密码校验
		if row.Get("password") != encrypt.MD5(c.Context.Param.GetString("password")) {
			c.ResponseErrorMessage(msg.DataPasswordError, c.Context.Param.GetString("password"))
			return
		}

		c.ResponseSuccess("登录成功", row)
	} else {
		c.Display("")
	}
	return
}

func (c *RCTController) Register() {
	if c.Context.IsPost() {
		//参数校验
		if c.Context.NotHasOrEmpty("username", "password", "password2") {
			c.ResponseErrorMessage(msg.ParamsMissing, nil)
			return
		}

		//存在校验
		_, err := model.UserModel().Where(&datatype.Row{"username": c.Context.Param.GetString("username")}).Find()
		if err == nil {
			c.ResponseErrorMessage(msg.DataAccountExists, nil)
			return
		}

		//插入数据
		data := datatype.Row{"username": c.Context.Param.GetString("username")}
		data.Set("password", weigo.MD5(c.Context.Param.GetString("password")))
		data.Set("status", 1)
		data.Set("register_time", datetime.DateTime())
		data.Set("register_ip", weigo.GetIP())

		id, err := model.UserModel().Insert(&data)
		if err != nil {
			c.ResponseErrorMessage(msg.SysError, err.Error())
			return
		}

		c.ResponseSuccess("注册成功", id)
	} else {
		//c.Display("")
		c.Context.ResponseString("OK")
		c.Context.ResponseSuccess("OK", nil)
	}
	return
}
